package com.ruoyi.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.entity.JrTemplates;
import com.ruoyi.entity.RecentLog;
import com.ruoyi.service.TemplatesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/template")
public class TemplatesController extends BaseController {
    @Autowired
    private TemplatesService templatesService;

    @GetMapping("/list")
    public TableDataInfo findAllTemplate(JrTemplates templates)
    {
        startPage();
        List<JrTemplates> list = templatesService.selectTemplateList(templates);
        return getDataTable(list);
    }

    //    保存历史记录
    @PostMapping("/updateLog")
    public void updateLog(@RequestBody RecentLog recentLog) {

        //  获取当前用户id
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Long userId = user.getUserId();
        recentLog.setUserId(userId);

        Date date =new Date();
        if(recentLog.getRecordsType().equals("p")){
            recentLog.setPreviewTime(date);
        }else {
            recentLog.setUpdataTime(date);
        }
        List<RecentLog> records = templatesService.selectLogRecords(recentLog.getUserId(),null);
        boolean contains = false;
        for(RecentLog record : records){
            if (record.getFileId() == recentLog.getFileId()){
                contains = true;
                break;
            }
        }
        if(records.size() < 10 && !contains){
            templatesService.addLogRecords(recentLog);
        }else {
            templatesService.updataLogRecords(recentLog);
        }
    }

    //    获取所有最近记录
    @GetMapping("/allRecords")
    public List<RecentLog> allRecords(String recordsType){
        System.out.println("查询最近记录"+recordsType);
        //  获取当前用户id
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Long userId = user.getUserId();

        return templatesService.selectLogRecords(userId,recordsType);
    }
}
